package cn.anlucky.apiadmin.service.impl;

import cn.anlucky.apiadmin.pojo.CustomException;
import cn.anlucky.apiadmin.pojo.Userinfo;
import cn.anlucky.apiadmin.service.LoginService;
import cn.anlucky.apiadmin.service.UserinfoService;
import cn.anlucky.apiadmin.vo.R;
import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private UserinfoService userinfoService;


    /**
     * 用户登录
     *
     * @param userinfo
     * @return
     */
    @Override
    public R login(Userinfo userinfo) {

        if (Objects.isNull(userinfo)) {
            throw new CustomException("用户对象为空，输入错误");
        }
        String username = userinfo.getUserName();
        String password = userinfo.getPassword();

        if (Strings.isBlank(username) || Strings.isBlank(password)){
            throw new CustomException("用户名和密码不能为空！");
        }


        LambdaQueryWrapper<Userinfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Userinfo::getUserName,userinfo.getUserName())
                .eq(Userinfo::getPassword,userinfo.getPassword());


        Userinfo loginUser = userinfoService.getOne(wrapper);

        if (Objects.isNull(loginUser)) {
            throw new CustomException("登录失败，用户名或密码错误！");
        }

        // 登录成功
        StpUtil.login(loginUser.getId(),new SaLoginModel()
                .setExtra("userName",loginUser.getUserName()));
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();

        return R.success("成功",tokenInfo.getTokenValue());
    }
}
